// pages/home/LocationCircle.js
let network = null;
let utils = null;
let api = null;
let constants = null;
const app = getApp();
var Zan = require('../../dist/index');
let WxNotificationCenter = require('../../utils/WxNotificationCenter.js');

Page(Object.assign({}, Zan.TopTips,{
  data: {
    region: null,
    city: null,
    district: null,
    circles: []
  },

  onLoad: function (options) {
    network = new app.NetWorkUtils();
    utils = new app.Utils();
    api = new app.Api();

    constants = new app.Constants();
    this.getLocation();
  },

  onReady: function () {
    // 生命周期函数--监听页面初次渲染完成

  },

  onShow: function () {
    // 生命周期函数--监听页面显示

  },

  onHide: function () {
    // 生命周期函数--监听页面隐藏

  },

  onUnload: function () {
    // 生命周期函数--监听页面卸载

  },

  onPullDownRefresh: function () {
    // 页面相关事件处理函数--监听用户下拉动作

  },

  onReachBottom: function () {
    // 页面上拉触底事件的处理函数

  },

  bindRegionChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      region: e.detail.value
    })
    network._post_json(this, api.getBusinessAreaList, { city: e.detail.value[1], district: e.detail.value[2]}, Success);
  },

  getLocation: function () {
    console.log("正在定位城市");
    this.setData({
      county: ''
    })
    const that = this;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        console.log(res);
        let latitude = res.latitude
        let longitude = res.longitude
        wx.request({
          url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${constants.key}`,
          success: res => {
            console.log(res)
            let location = res.data.result.ad_info;
            that.setData({
              city: location.city,
              district: location.district,
              region: [location.province, location.city, location.district]
            })
            network._post_json(that, api.getBusinessAreaList, { city: location.city }, Success);
          }
        })
      }
    })
  },

  /**
   * 选择商圈
   */
  chooseCircle: function (e) {
    let circle = {};
    circle.city = this.data.region[1];
    circle.district = e.currentTarget.dataset.district;
    circle.id = e.currentTarget.dataset.id;
    circle.name = e.currentTarget.dataset.name;
    WxNotificationCenter.postNotificationName("RefreshHome", circle);
    wx.navigateBack();
  }
}))

var Success = function (that, res) {
  if (res.data.data) {
    that.setData({
      circles: res.data.data
    })
    if (res.data.data[0].businessAreas.length < 1) {
      that.showZanTopTips(that.prompt, '暂无商圈');
    }
  }
}
